import heapq

import numpy as np

from db_conn.getBy import getByProvinceAndYear, getByProvince


#获得合作最多的单位对数据层
def getCoorCntService(province):
    completion = {}  # 全部单位的列表存为哈希
    # data = getByProvinceAndYear(province, year)
    data = getByProvince(province)
    for d in data:
        if d[2] != None:
            d2 = d[2].split('、')
            for com in d2:
                completion[com] = 1
    # 存为哈希（name:index）
    len1 = len(completion)
    print(len1)
    com_dict = {}
    index = 0
    for com in completion:
        com_dict[com] = index
        index = index + 1
    print(com_dict)
    # 存为哈希（index:name)
    index_dict = {}
    for com in com_dict:
        index_dict[com_dict.get(com)] = com
    print(index_dict)
    # 初始化关系矩阵
    array = np.zeros((len1, len1))  # 长度为l的二维数组，初始化为0
    # 遍历合作关系
    for d in data:
        if d[2] != None:
            d2 = d[2].split('、')  # 获得一次合作的所有单位
            for com1 in d2:
                for com2 in d2:
                    if com2 != com1:  # 同一个就不加
                        array[com_dict[com1]][com_dict[com2]] = array[com_dict[com1]][com_dict[com2]] + 1
    # 查找合作次数最多的15次
    # 存成哈希列表（n,cnt）,n=h*len+l
    dict_temp = {}
    for h in range(len1):
        for l in range(h):
            dict_temp[h * len1 + l] = array[h][l]
    heap = list(dict_temp.values())
    # heapq.heapify(heap)
    listMax15 = heapq.nlargest(15, heap)
    print(listMax15[len(listMax15) - 1])
    max = listMax15[len(listMax15) - 1]
    max15Coor = []
    for i in dict_temp.keys():
        if dict_temp.get(i) >= max:
            coor = {}
            coor['name1'] = index_dict[int(i / len1)]
            coor['name2'] = index_dict[i % len1]
            coor['value'] = dict_temp.get(i)
            max15Coor.append(coor)
    sort = sorted(max15Coor, key=lambda x: x['value'], reverse=True)
    print(sort)
    return sort


if __name__ == '__main__':
    getCoorCntService('黑龙江')
